package com.isczy.acl.service.impl;

import com.isczy.acl.entity.User;
import com.isczy.acl.service.PermissionService;
import com.isczy.acl.service.UserService;
import com.isczy.serurity.entity.SecurityUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * <p>
 * 自定义userDetailsService - 认证用户详情
 * 必须实现UserDetailsService重写loadUserByUsername方法
 * </p>
 */
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private PermissionService permissionService;

    /***
     * ***************************************
     * 功能描述:根据账号获取用户信息
     * @param username
     * @return {@link UserDetails}
     * @author create: TODO 人员:【ChangZiYang】类型:【新增方法】日期:【2021-01-26 16:37】
     * @author modify:
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 从数据库中取出用户信息
        User user = userService.selectByUsername(username);

        // 判断用户是否存在
        if (null == user){
            throw new UsernameNotFoundException("用户名不存在！");
        }
        // 返回UserDetails实现类
        com.isczy.serurity.entity.User curUser = new com.isczy.serurity.entity.User();
        BeanUtils.copyProperties(user,curUser);
        //查询用户菜单
        List<String> authorities = permissionService.selectPermissionValueByUserId(user.getId());
        //设置用户信息及菜单权限
        SecurityUser securityUser = new SecurityUser(curUser);
        securityUser.setPermissionValueList(authorities);
        return securityUser;
    }

}
